package com.plan.base.util;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Web工具类
 *
 * @author zcl
 */
@Slf4j
public class WebTool {

    /**
     * 获取本地IP地址
     *
     * @return IP
     */
    public static String getLocalIp() {
        try {
            if (isWindowsOs()) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return getLinuxLocalIp();
            }
        } catch (Exception e) {
            log.error("获取本地IP地址错误", e);
            return null;
        }
    }


    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     */
    private static String getLinuxLocalIp() {
        String ip = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface networkInterface = en.nextElement();
                String name = networkInterface.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                                log.debug("Found IP address: {}", ipaddress);
                                break;
                            }
                        }
                    }
                }
                if (ip != null) {
                    // 找到了IP 提前结束循环
                    break;
                }
            }
        } catch (Exception e) {
            log.error("获取LinuxIP地址错误", e);
        }
        return ip;
    }


    /**
     * 判断操作系统是否是Windows
     *
     * @return true是，false不是
     */
    public static boolean isWindowsOs() {
        String osName = System.getProperty("os.name");
        return osName.toLowerCase().contains("windows");
    }


}

